<template>
  <div class="login_page">
    <div class="login_box">
      <div class="txt">
        <h3>经历网，为留住您的真实经历而生！<br>
          <span style="font-size: 20px;">Born to keep your true experience!</span></h3>
      </div>
      <div class="center_box">
        <!-- 找回密码&登录-->
        <div :class="{login_form: true, rotate: tab == 2}">
          <div :class="{tabs: true, r180: reverse == 2}">
            <div class="fl tab" @click="changetab(1)">
              <span :class="{on: tab == 1}">找回密码</span>
            </div>
            <div class="fl tab" @click="changetab(2)">
              <span :class="{on: tab == 2}">登录</span>
            </div>
          </div>
          <!-- 找回密码 -->
          <div class="form_body" v-if="reverse == 1">
            <!-- submit.prevent 阻止默认表单事件提交，采用loginSubmit -->
            <form @submit.prevent="regSubmit">
              <input type="text" v-model="findPwdData.phone" placeholder="请输入11位手机号" autocomplete="off"
                     style="width: 196px"> &nbsp;
              <button v-if="!sending" class="button" @click="send()">
                获取验证码
              </button>
              <button v-else disabled class="button disabled">
                {{ leftSecond }} 秒后重发
              </button>
              <input style="width: 200px" type="password" v-model="findPwdData.code" placeholder="请输入验证码"
                     autocomplete="off">
              <input type="password" v-model="findPwdData.newPassword"
                     placeholder="请输入新密码，6-20 位，可用数字/字母/符号组合"
                     autocomplete="off">
              <input type="password" v-model="findPwdData.repPassword" placeholder="确认新密码">
              <div class="error_msg">{{ regMessage }}</div>
              <p class="find" @click="register">我要注册</p>
              <input type="submit" v-if="subState" disabled="disabled" value="提交中 ···" class="btn">
              <input type="submit" v-else value="修改密码" class="btn">
            </form>
          </div>
          <!-- 登录 -->
          <div class="form_body r180" v-if="reverse == 2">
            <form @submit.prevent="loginSubmit">
              <input type="text" v-model="loginData.username" placeholder="请输入用户名"
                     autocomplete="off">
              <input type="password" v-model="loginData.password" placeholder="请输入密码"
                     autocomplete="off">
              <div class="error_msg">{{ loginMessage }}</div>
              <input type="submit" v-if="subState" disabled="disabled" value="登录中 ···" class="btn"/>
              <input type="submit" v-else value="登录" @submit="loginSubmit" class="btn"/>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// 数据校验工具类
import {isvalidUsername, isvalidPassword, isvalidPhone} from "@/utils/validate";
import {checkPhoneVerificationCode, findUserPassword} from '@/api/auth'

export default {
  name: 'Retrieve',

  data() {
    return {
      tab: 1, // 高亮当前标签名
      reverse: 1, // 旋转 1 登录，2 注册
      loginMessage: '', // 登录错误提示信息
      regMessage: '', // 注册错误提示信息
      subState: false, // 提交状态
      redirectURL: '//localhost:3000', // 登录成功后重写向地址
      loginData: { // 登录表单数据
        username: '',
        password: ''
      },
      findPwdData: { // 注册表单数据
        newPassword: '',
        repPassword: '',
        phone: '',
        code: ''
      },
      sending: false, // 是否发送验证码
      second: 60, // 倒计时间
      leftSecond: 0, // 剩余时间
    }
  },
  async created() {
    // 获取来源地址
    if (this.$route.query.redirectURL) {
      this.redirectURL = this.$route.query.redirectURL
    }
  },

  methods: {
    register() {
      this.$router.push('/')
    },
    /**
     * 切换标签
     */
    changetab(int) {
      this.tab = int;
      let _that = this;
      setTimeout(() => {
        this.reverse = int
      }, 200)
    },
    /**
     * 提交登录表单
     */
    loginSubmit() {
      // 正在登录中,不能重复提交
      if (this.subState) {
        return false
      }
      // 校验用户名
      if (!isvalidUsername(this.loginData.username)) {
        this.loginMessage = '请输入用户名，2-20位，可用中文、数字、字母和下划线组合'
        return false
      }

      // 校验密码
      if (this.loginData.password.length < 6 || this.loginData.password.length > 30) {
        this.loginMessage = '请输入 6-30 位密码，区分大小写且不可有空格'
        return false
      }
      // 校验密码
      if (!isvalidPassword(this.loginData.password)) {
        this.loginMessage = '请输入正确的密码'
        return false
      }
      this.subState = true; // 登录中...

      // 触发 /store/modules/auth.js actions 中的 UserLogin 方法名 提交登录数据
      this.$store.dispatch('UserLogin', this.loginData).then(response => {

        const {code, message} = response

        if (code === 20000) {
          window.location.href = this.redirectURL // 跳转回来源地址,引发登录页面的地址
        } else {
          this.loginMessage = message
        }
        this.subState = false;
        // eslint-disable-next-line no-unused-vars
      }).catch(error => {
        this.subState = false
        this.loginMessage = '系统繁忙，请稍后重试'
      });
    },
    /**
     * 发送手机短信
     * @returns {Promise<boolean>}
     */
    async send() {

      if (!this.findPwdData.phone) {
        this.regMessage = '手机号码不能为空'
        return false
      }

      // 校验用户名(调用校验文件方法)
      if (!isvalidPhone(this.findPwdData.phone)) {
        this.regMessage = '请输入合法手机号码'
        return false
      }

      // 防止重复提交
      if (this.sending) return
      this.sending = true  // 显示倒计时

      //倒计时
      this.timeDown()
      const {code, message} = await checkPhoneVerificationCode(this.findPwdData.phone)
      if (code !== 20000) {
        this.leftSecond = null // 清空倒计时间
        this.regMessage = message
        return false
      }

    },

    /**
     * 获取验证码倒计时
     */
    timeDown() {
      this.leftSecond = this.second
      const timmer = setInterval(() => {
        this.leftSecond--
        if (this.leftSecond <= 0) {
          //停止计时
          clearInterval(timmer)
          this.sending = false
        }
      }, 1000)
    },

    /**
     * 提交注册
     * @returns {Promise<boolean>}
     */
    async regSubmit() {
      // 注册中,不能重复提交
      if (this.subState) {
        return false
      }
      // 校验手机号(调用校验文件方法)
      if (!isvalidPhone(this.findPwdData.phone)) {
        this.regMessage = '请输入合法手机号码'
        return false
      }
      // 校验手机验证码
      if (this.findPwdData.code.length < 6 || this.findPwdData.code.length > 6) {
        this.regMessage = '请输入验证码';
        return false;
      }
      // 校验密码   : '', repPassword
      if (this.findPwdData.newPassword.length < 6 || this.findPwdData.newPassword.length > 20) {
        this.regMessage = '请输入 6-20 位密码,区分大小写且不可有空格'
        return false
      }
      // 校验密码
      if (!isvalidPassword(this.findPwdData.newPassword)) {
        this.regMessage = '请输入正确格式的密码'
        return false
      }
      // 校验密码和确认密码是否一致
      if (this.findPwdData.newPassword !== this.findPwdData.repPassword) {
        this.regMessage = '两次输入的密码不一致'
        return false
      }
      this.subState = true // 提交中....
      // 提交修改密码表单
      findUserPassword(this.findPwdData).then(response => {
        this.subState = false // 提交中
        const {code, message} = response
        if (code === 20000) {
          // 注册成功,切换到登录页面
          this.changetab(2)
          // alert('恭喜您,密码修改成功!')
          this.loginMessage = '恭喜您，密码修改成功！请登录！'
        } else {
          this.regMessage = message
        }
        // eslint-disable-next-line no-unused-vars
      }).catch(error => {
        this.subState = false
        this.regMessage = '系统繁忙，请稍后重试'
      })
    }
  }
}
</script>
<style scoped>
@import '../../assets/style/login.css';

@media only screen and (min-width: 960px) {

  /* 网站说明文字 */
  .txt {
    padding-top: 10px;
    color: #eee;
    text-align: center;
    font-size: 18px;
    line-height: 30px;
  }
}

/* 获取验证码按钮 */
.button {
  display: inline-block;
  color: white;
  padding: 0 10px;
  height: 45px;
  line-height: 45px;
  text-align: center;
  background: #345dc2;
  border-radius: 3px;
  margin-left: 5px;
  cursor: pointer;
  border: 0;
}

.find {
  text-align: right;
  font-size: 14px;
  color: #355bbb;
  margin-right: 10px;
}

/* 手机端 获取验证码按钮 */
@media only screen and (max-width: 960px) {
  .button {
    padding: 0 3%;
  }

  /* 网站说明文字 */
  .txt {
    padding-top: 40px;
    color: #eee;
    text-align: center;
    font-size: 18px;
    line-height: 30px;
  }
}
</style>

